package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.service.*;
import com.example.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 商品
 * @author: xxx
 * @create: 2021/7/19 09:30
 */
@RestController
@RequestMapping("goods")
public class GoodsController {

    @Autowired
    private GoodsService service;
    @Autowired
    private HszMoneyService hszMoneyService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CommissionService commissionService;
    @Autowired
    private CouponService couponService;

    @Autowired
    private GetCreditsService getCreditsService;

    /**
     * @param json
     * @description: 分页
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getPage")
    public Result getPage(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        List<Map<String, Object>> list = service.getList(jsonObject);
        int total = service.getCount(jsonObject);

        return ResultUtil.successPage(list, total);
    }

    /**
     * @param
     * @description: 列表
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getList")
    public Result getList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        return ResultUtil.success(service.getList(jsonObject));
    }

    /**
     * @param json
     * @description: 申请上架分页
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getGoodsAddedPage")
    public Result getGoodsAddedPage(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        List<Map<String, Object>> list = service.getListGoodsAdded(jsonObject);
        int total = service.getCountGoodsAdded(jsonObject);

        return ResultUtil.successPage(list, total);
    }

    /**
     * @param
     * @description: 申请上架列表
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getGoodsAddedList")
    public Result getGoodsAddedList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        return ResultUtil.success(service.getListGoodsAdded(jsonObject));
    }

    /**
     * @param map
     * @description: 申请上架详情
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getGoodsAddedById")
    public Result getGoodsAddedById(@RequestBody Map<String, Object> map) {

        return ResultUtil.success(service.getGoodsAddedById(map));
    }

    /**
     * @param json
     * @description: 获取营业时间
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/21 9:19
     */
    @RequestMapping("getTimeList")
    public Result getTimeList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        if (TokenTool.getPermissionType().equals("m")) {
            return ResultUtil.success(service.getTimeList(jsonObject));
        } else {
            return ResultUtil.error(-500, "无权限！");
        }
    }

    /**
     * @param
     * @description: 审核上架
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("audit")
    @Transactional(rollbackFor = Exception.class)
    public Result audit(@RequestBody Map<String, Object> map) throws Exception {
        // 查询商品信息
        Map<String, Object> mapGoodsAdded = service.getGoodsAddedById(map);
        Map<String, Object> mapGoodsId = new HashMap<>();
        mapGoodsId.put("id", mapGoodsAdded.get("goodsId"));
        Map<String, Object> mapGoods = service.getById(mapGoodsId);
        // 判断商品状态是否==1
        if (mapGoodsAdded.get("status").toString().equals("1")) {
            // 已售状态
            if (mapGoods.get("added").toString().equals("4")) {
                // 修改商品信息
                Map<String, Object> mapNew = new HashMap<>();
                mapNew.put("id", mapGoods.get("id"));
                mapNew.put("added", 1);
                mapNew.put("price", mapGoods.get("newPrice").toString());
                service.update(mapNew);//上架
                map.put("status", 2);
                service.updateGoodsAdded(map);//更新申请状态
                // 获取用户积分
                Map<String, Object> params = new HashMap();
                params.put("id", mapGoods.get("uId"));
                Map<String, Object> UserCredits = getCreditsService.getMyCredits(params);
                // 计算剩余积分
                BigDecimal total = new BigDecimal(Double.valueOf(UserCredits.get("total").toString()));  // 账户目前可用积分 total
                BigDecimal gCredit = new BigDecimal(Double.valueOf(mapGoods.get("getCredits").toString()));// 此单获取积分
                BigDecimal tdMoney = total.add(gCredit).setScale(2, BigDecimal.ROUND_HALF_UP);// 加法四舍五入保留两位小数

                // 添加一条上架获取的积分记录 自己获得1%积分
                Map<String, Object> creditsMap = new HashMap<>();
                creditsMap.put("id", IDTool.getUUID32());
                creditsMap.put("userId", mapGoods.get("uId"));
                creditsMap.put("userName", mapGoods.get("uName"));
                creditsMap.put("userPhone", mapGoods.get("phone"));
                creditsMap.put("putawayShopName", mapGoods.get("name"));
                creditsMap.put("putawayShopSn", mapGoods.get("sn"));
                creditsMap.put("putawayShopPrice", mapGoods.get("price"));
                creditsMap.put("getCredits", mapGoods.get("getCredits")); // 获得积分
                creditsMap.put("accountCredits", tdMoney); // 账户剩余积分 accountCredits
                getCreditsService.saveAdd(creditsMap);

            } else {
                return ResultUtil.error(-500, "商品状态不符合上架条件");
            }
        } else {
            return ResultUtil.error(-500, "已审核过");
        }

        return ResultUtil.success();
    }

    /**
     * @param
     * @description: 取消上架
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("cancelAudit")
    @Transactional(rollbackFor = Exception.class)
    public Result canelAudit(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> mapGoodsAdded = service.getGoodsAddedById(map);
        Map<String, Object> mapGoodsId = new HashMap<>();
        mapGoodsId.put("id", mapGoodsAdded.get("goodsId"));
        Map<String, Object> mapGoods = service.getById(mapGoodsId);
        if (mapGoodsAdded.get("status").toString().equals("1")) {
            if (mapGoods.get("added").toString().equals("4")) {
                if (mapGoodsAdded.get("couponId") != null) {
                    Map<String, Object> mapCouponId = new HashMap<>();
                    mapCouponId.put("id", mapGoodsAdded.get("couponId"));
                    mapCouponId.put("userId", mapGoodsAdded.get("userId"));
                    mapCouponId.put("status", 1);
                    couponService.updateCouponDetail(mapCouponId);//返回核销优惠券
                }
                if (mapGoodsAdded.get("money") != null && Double.parseDouble(mapGoodsAdded.get("money").toString()) > 0) {
                    Map<String, Object> mapId = new HashMap<>();
                    mapId.put("id", mapGoodsAdded.get("userId"));
                    Map<String, Object> commissionMap = commissionService.getById(mapId);
                    Map<String, Object> mapCommission = new HashMap<>();
                    mapCommission.put("id", mapGoodsAdded.get("userId"));
                    BigDecimal moneyPrice = new BigDecimal(Double.parseDouble(mapGoodsAdded.get("money").toString()));
                    Double money = Double.parseDouble(commissionMap.get("money").toString());
                    Double oldMoney = Double.parseDouble(commissionMap.get("oldMoney").toString());
                    mapCommission.put("money", new BigDecimal(money).add(moneyPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    mapCommission.put("oldMoney", new BigDecimal(oldMoney).subtract(moneyPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    mapCommission.put("uuid", commissionMap.get("uuid"));
                    mapCommission.put("uuidNew", IDTool.getUUID32());
                    Integer result = commissionService.update(mapCommission);//更新佣金
                    if (result <= 0) {
                        throw new Exception("取消上架失败");
                    }
                    //佣金设置为已驳回
                    Map<String, Object> mapWithdraw = new HashMap<>();
                    mapWithdraw.put("id", mapGoodsAdded.get("withdrawId"));
                    mapWithdraw.put("status", 3);
                    commissionService.updateWithdraw(mapWithdraw);
                }
                Map<String, Object> mapNew = new HashMap<>();
                mapNew.put("id", mapGoods.get("id"));
                mapNew.put("added", 2);
                service.update(mapNew);
                map.put("status", 3);
                service.updateGoodsAdded(map);//更新申请状态
            } else {
                return ResultUtil.error(-500, "商品状态不符合取消上架条件");
            }
        } else {
            return ResultUtil.error(-500, "已审核过");
        }


        return ResultUtil.success();
    }

    /**
     * @param
     * @description: 商品上架
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("auditGoods")
    @Transactional(rollbackFor = Exception.class)
    public Result auditGoods(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> mapGoods = service.getById(map);
        if (mapGoods.get("added").toString().equals("2")) {
            Map<String, Object> mapNew = new HashMap<>();
            mapNew.put("id", mapGoods.get("id"));
            mapNew.put("added", 1);
            service.update(mapNew);

            Map<String, Object> mapUs = new HashMap<>();
            mapUs.put("studioId", mapGoods.get("studioId"));
            Map<String, Object> mapUser = userService.getByStudioId(mapUs);
            if (mapUser != null) {
                Map<String, Object> mapHszMoney = new HashMap<>();
                mapHszMoney.put("id", mapUser.get("id").toString() + mapGoods.get("studioId"));
                Map<String, Object> commission = hszMoneyService.getById(mapHszMoney);
                BigDecimal commissionMoney = new BigDecimal(Double.parseDouble(commission.get("money").toString()));
                BigDecimal addMoney = new BigDecimal(Double.parseDouble(mapGoods.get("addPrice").toString()));
                mapHszMoney.put("money", commissionMoney.add(addMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
                mapHszMoney.put("uuid", commission.get("uuid"));
                mapHszMoney.put("uuidNew", IDTool.getUUID32());
                Integer result = hszMoneyService.update(mapHszMoney);
                if (result <= 0) {
                    throw new Exception("更新失败");
                }
            } else {
                return ResultUtil.error(-500, "画室长为空");
            }

        } else {
            return ResultUtil.error(-500, "不符合上架条件");
        }

        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 详情
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getById")
    public Result getById(@RequestBody Map<String, Object> map) {

        return ResultUtil.success(service.getById(map));
    }

    /**
     * @param map
     * @description: 详情
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getTimeById")
    public Result getTimeById(@RequestBody Map<String, Object> map) {

        return ResultUtil.success(service.getTimeById(map));
    }

    /**
     * @param map
     * @description: 查询每人每日购买次数
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getBuyNums")
    public Result getBuyNums(@RequestBody Map<String, Object> map) {
        String key = "preOrder:buyNums";
        return ResultUtil.success(redisUtil.get(key));
    }

    /**
     * @param map
     * @description: 保存
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("save")
    public Result save(@RequestBody Map<String, Object> map) {

        map.put("id", IDTool.getUUID32());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        map.put("sn", simpleDateFormat.format(new Date()));
        if (map.get("uId") != null && StringUtils.isNotBlank(map.get("uId").toString())) {
            map.put("uId", map.get("uId"));
            service.save(map);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-500, "请选择持有人");
        }


    }

    /**
     * @param map
     * @description: 设置每人每日购买次数
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("updateBuyNums")
    public Result updateBuyNums(@RequestBody Map<String, Object> map) {
        String key = "preOrder:buyNums";
        redisUtil.set(key, map.get("buyNums").toString());
        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 修改
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("update")
    public Result update(@RequestBody Map<String, Object> map) {
        service.update(map);
        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 修改营业时间
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/21 9:19
     */
    @RequestMapping("updateTime")
    public Result updateTime(@RequestBody Map<String, Object> map) {

        service.updateTime(map);
        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 删除
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("delete")
    public Result delete(@RequestBody Map<String, Object> map) {
        service.delete(map);
        return ResultUtil.success();
    }
}
